package com.anolesoft.yr.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class SQLUtil {
	public static void main(String[] args) {
		String str1 = "update am_billing_info\r\n"
				+ "   set\r\n"
				+ "       receive_user      = v_receive_user,\r\n"
				+ "       receive_time      = v_receive_time,\r\n"
				+ "       receive_notes     = v_receive_notes,\r\n"
				+ "       receive_state     = v_receive_state,\r\n"
				+ "       refuse_reason     = v_refuse_reason,\r\n"
				+ "       m_user            = v_m_user,\r\n"
				+ "       m_time            = sysdate\r\n"
				+ " where objuid = v_objuid\r\n"
				+ "" ;  
;
		String formatSQLmyBatis = formatSQLmyBatis(str1);
		
		System.out.println(formatSQLmyBatis);
	}

	private static String formatSQLmyBatis(String str) {
		String word = "v_";
		List<String> findWords = new ArrayList<>();
		int index = 0;
		while (true) {
			index = str.indexOf(word, index);
			int indexEnd = str.indexOf(",", index);
			if (indexEnd == -1) {
				indexEnd = str.indexOf(")", index);
				if (indexEnd == -1) {
					indexEnd = str.indexOf("\r\n", index);
				}
			}
			if (index == -1) {
				break;
			}

			String substring = str.substring(index, indexEnd);

			index = indexEnd;
			findWords.add(substring);
		}

		Map<String, String> collect = findWords.stream().distinct().collect(Collectors.toMap(w -> {
			return w;
		}, w -> {
			String w1 = w.replace(word, "");
			return "#{" + toCamelCase(w1) + "}";
		}));

		for (String key : collect.keySet()) {
			str = str.replaceAll(key, collect.get(key));
		}

		return str;
	}

	public static String toCamelCase(String underlineStr) {
		if (underlineStr == null) {
			return null;
		}
		// 分成数组
		char[] charArray = underlineStr.toCharArray();
		// 判断上次循环的字符是否是"_"
		boolean underlineBefore = false;
		StringBuffer buffer = new StringBuffer();
		for (int i = 0, l = charArray.length; i < l; i++) {
			// 判断当前字符是否是"_",如果跳出本次循环
			if (charArray[i] == 95) {
				underlineBefore = true;
			} else if (underlineBefore) {
				// 如果为true，代表上次的字符是"_",当前字符需要转成大写
				buffer.append(charArray[i] -= 32);
				underlineBefore = false;
			} else {
				// 不是"_"后的字符就直接追加
				buffer.append(charArray[i]);
			}
		}
		return buffer.toString();
	}
}
